from datetime import datetime
from io import BytesIO
import os
import re
import time
import uuid
from django.test import TestCase
import fitz
from flask import json
import openpyxl
import pandas as pd
from openpyxl import load_workbook
import requests
from doc_service.models import Report
from .yida_config import YidaClient
from oss_service.views import bucket,ds_bucket
import redis
import logging
from django.core.cache import cache
from yida_app_service.chengxiang.xm_cloud_config import XmCloudClient
xm_client = XmCloudClient()
logger = logging.getLogger(__name__)
logging.basicConfig(
    filename='output.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
client = redis.StrictRedis(
    host='10.8.0.83',
    port=6379,
    db=3,
    password=None,
    decode_responses=True
)

bak_r = redis.StrictRedis(
    host='10.8.0.83',
    port=6379,
    db=13,
    password=None,
    decode_responses=True
)
admin_user_id = "034728252633647035"
report_form_uuid = "FORM-0BC04FECE4F544B297D37901915570D2OEIY"
finicial_form_uuid = "FORM-BAFAA96000BA4C44A0C8F3256EB00407RP4T"
person_form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG"
yida_client = YidaClient()

class YidaTest(TestCase):
    def setUp(self) -> None:
        return super().setUp()
    
    def test_update_filed(self):
        '''修改字段'''
        for index,report_code in enumerate([
"CXAF-JD-2500101"
        ]):
            print(f"正在修改第{index+1}条：{report_code}")
            sn_code = 10309
            result = yida_client.update_form_data_by_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                    admin_user_id,
                                                    search_field=[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report_code
                                                        }
                                                    ],
                                                    update_field={
                                                        # "textField_lqetx3jq":"潘百琴", # 业务员
                                                        # "textField_lp93kxup":"CXEF-WX-2303670", #报告编号
                                                        # "selectField_lqx655zl":"委托检测检查", # 检测类别
                                                        # "textField_lv25b13o":"检测检查报告", # 报告标题
                                                        # "textField_lqbsdaaj":"6ED66J913FCHY6ON8CB4J41UU5883RQQF3WQLXV6", # 模版编号
                                                        # "textField_lvg2c3u6":f"F24{str(sn_code+index).zfill(5)}", # 归档编号
                                                        # "textField_lvg2c3u6":f"F2409676", # 归档编号
                                                        # "textField_lvg2c3u4":"F25",
                                                        # "textField_lpb5xuuu":"NB-NH-KK-2025-16128", # 监管编号
                                                        # "employeeField_lqkmu48d":["024021201326222852"], # 一级总工
                                                        # "employeeField_lq4t9qtu":[], # 三级总工
                                                        # "selectField_lqvpbi42":"043050546726320277", # 组长（专家）
                                                        # "selectField_lqvpbi43":"2569602548793559", # 组员1（专家）
                                                        # "selectField_lqvpbi45":"040731181626440455", # 组员2（专家）
                                                        # "multiSelectField_lqwcqyd1":["1203591811846049","132058133925879495"], #组长组员id
                                                        # "employeeField_lqwgfnad":["1203591811846049","132058133925879495"], # 组长组员成员
                                                        # "textField_ltmlzgdv":"", # 签署信息
                                                        # "selectField_lpb4vtbt":"检测检查报告", #报告名称
                                                        # "selectField_lpgut0ng":"薛德力-04011267414561", # 检测1
                                                        # "textField_ltgomz9t":"薛德力",# 检测1name
                                                        # "selectField_lqeidrd3":"张东军-0255646861738", #检测2
                                                        # "selectField_mbhlc9nn":"方勐-1232135462828471", # 检测3
                                                        # "textField_lphpacz4":"桐庐县百江镇人民政府", #委托方
                                                        # "textField_lp93kxwq":"2000", #总检测费
                                                        # "textField_lqetx3jq":"潘百琴",
                                                        # "selectField_lqwcqyd0":"04396438451212628", #编制员
                                                        # "employeeField_m1k1eva6":["04396438451212628"], #编制员成员
                                                        # "dateField_lphnrozp":1693526400000, # 委托日期
                                                        # "dateField_lpb39cyx": 1717977600000,# 签发日期
                                                        # "dateField_lp93kxx6": 1693526400000, #检测日期
                                                        # "dateField_lpgnxeft":1699488000000, #检测日期至
                                                        # "selectField_lp93kxv5":"委托检测检查", #工程类别
                                                        "textField_lphpacz0":"更楼融富府小区地下室D152车位", #工程名称
                                                        # "attachmentField_lqrz4ehj":[
                                                        #                                 {
                                                        #                                 "downloadUrl": f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/out-pdf/202412/90bb0544-f7cb-46c5-8c4a-e156206f782f/attachmentField_lqrz4ehj/0-01623 浙江巨化热电有限公司节能增效技改项目.pdf",
                                                        #                                 "name": "01623 浙江巨化热电有限公司节能增效技改项目#12、#13机组 11.8.pdf",
                                                        #                                 "previewUrl": f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/out-pdf/202412/90bb0544-f7cb-46c5-8c4a-e156206f782f/attachmentField_lqrz4ehj/0-01623 浙江巨化热电有限公司节能增效技改项目.pdf",
                                                        #                                 "url": f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/out-pdf/202412/90bb0544-f7cb-46c5-8c4a-e156206f782f/attachmentField_lqrz4ehj/0-01623 浙江巨化热电有限公司节能增效技改项目.pdf",
                                                        #                                 "ext": "pdf"
                                                        #                                 }
                                                        #                             ]
                                                    })
        pass
    

    def test_update_finicial_filed(self):
        '''修改字段'''
        for index,report in enumerate([
("CXAFH-YH-2400159","杭政储出（2023)112地块8号楼1单元201室				"),
("CXAFH-YH-2400160","杭政储出（2023)112地块8号楼1单元202室				"),
("CXAFH-YH-2400161","杭政储出（2023)112地块8号楼1单元301室				"),
("CXAFH-YH-2400162","杭政储出（2023)112地块8号楼1单元302室				"),
("CXAFH-YH-2400163","杭政储出（2023)112地块8号楼1单元501室				"),
("CXAFH-YH-2400164","杭政储出（2023)112地块8号楼1单元502室				"),
("CXAFH-YH-2400165","杭政储出（2023)112地块8号楼1单元601室				"),
("CXAFH-YH-2400166","杭政储出（2023)112地块8号楼1单元602室				"),
("CXAFH-YH-2400167","杭政储出（2023)112地块8号楼1单元701室				"),
("CXAFH-YH-2400168","杭政储出（2023)112地块8号楼1单元702室				"),
("CXAFH-YH-2400169","杭政储出（2023)112地块8号楼1单元801室				"),
("CXAFH-YH-2400170","杭政储出（2023)112地块8号楼1单元802室				"),
("CXAFH-YH-2400171","杭政储出（2023)112地块8号楼1单元901室				"),
("CXAFH-YH-2400172","杭政储出（2023)112地块8号楼1单元902室				"),
("CXAFH-YH-2400173","杭政储出（2023)112地块8号楼1单元1001室				"),
("CXAFH-YH-2400174","杭政储出（2023)112地块8号楼1单元1002室				"),
("CXAFH-YH-2400175","杭政储出（2023)112地块8号楼1单元1101室				"),
("CXAFH-YH-2400176","杭政储出（2023)112地块8号楼1单元1102室				"),
("CXAFH-YH-2400177","杭政储出（2023)112地块8号楼1单元1201室				"),
("CXAFH-YH-2400178","杭政储出（2023)112地块8号楼1单元1202室				"),
("CXAFH-YH-2400179","杭政储出（2023)112地块8号楼1单元1301室				"),
("CXAFH-YH-2400180","杭政储出（2023)112地块8号楼1单元1302室				"),
("CXAFH-YH-2400181","杭政储出（2023)112地块8号楼1单元1401室				"),
("CXAFH-YH-2400182","杭政储出（2023)112地块8号楼1单元1402室				"),
("CXAFH-YH-2400183","杭政储出（2023)112地块8号楼1单元1501室				"),
("CXAFH-YH-2400184","杭政储出（2023)112地块8号楼1单元1502室				"),
("CXAFH-YH-2400185","杭政储出（2023)112地块8号楼1单元1601室				"),
("CXAFH-YH-2400186","杭政储出（2023)112地块8号楼1单元1602室				"),
("CXAFH-YH-2400187","杭政储出（2023)112地块8号楼1单元1701室				"),
("CXAFH-YH-2400188","杭政储出（2023)112地块8号楼1单元1702室				"),
("CXAFH-YH-2400189","杭政储出（2023)112地块8号楼1单元1801室				"),
("CXAFH-YH-2400190","杭政储出（2023)112地块8号楼1单元1802室				"),
("CXAFH-YH-2400191","杭政储出（2023)112地块8号楼1单元1901室				"),
("CXAFH-YH-2400192","杭政储出（2023)112地块8号楼1单元1902室				"),
("CXAFH-YH-2400193","杭政储出（2023)112地块8号楼1单元2001室				"),
("CXAFH-YH-2400194","杭政储出（2023)112地块8号楼1单元2002室				"),
("CXAFH-YH-2400195","杭政储出（2023)112地块8号楼1单元2101室				"),
("CXAFH-YH-2400196","杭政储出（2023)112地块8号楼1单元2102室				"),
("CXAFH-YH-2400197","杭政储出（2023)112地块8号楼1单元2201室				"),
("CXAFH-YH-2400198","杭政储出（2023)112地块8号楼1单元2202室				"),
("CXAFH-YH-2400199","杭政储出（2023)112地块8号楼1单元2301室				"),
("CXAFH-YH-2400200","杭政储出（2023)112地块8号楼1单元2302室				"),
("CXAFH-YH-2400201","杭政储出（2023)112地块8号楼1单元2401室				"),
("CXAFH-YH-2400202","杭政储出（2023)112地块8号楼1单元2402室				"),
("CXAFH-YH-2400203","杭政储出（2023)112地块8号楼1单元2501室				"),
("CXAFH-YH-2400204","杭政储出（2023)112地块8号楼1单元2502室				"),
("CXAFH-YH-2400250","杭政储出（2023)112地块10号楼1单元2502室				"),
("CXAFH-YH-2400251","杭政储出（2023)112地块10号楼1单元2601室				"),
("CXAFH-YH-2400252","杭政储出（2023)112地块10号楼1单元2602室				"),
("CXAFH-YH-2400253","杭政储出（2023)112地块10号楼1单元203室				"),
("CXAFH-YH-2400254","杭政储出（2023)112地块10号楼1单元204室				"),
("CXAFH-YH-2400255","杭政储出（2023)112地块10号楼1单元404室				"),
("CXAFH-YH-2400256","杭政储出（2023)112地块10号楼1单元503室				"),
("CXAFH-YH-2400257","杭政储出（2023)112地块10号楼1单元504室				"),
("CXAFH-YH-2400258","杭政储出（2023)112地块10号楼1单元603室				"),
("CXAFH-YH-2400259","杭政储出（2023)112地块10号楼1单元604室				"),
("CXAFH-YH-2400260","杭政储出（2023)112地块10号楼1单元703室				"),
("CXAFH-YH-2400261","杭政储出（2023)112地块10号楼1单元704室				"),
("CXAFH-YH-2400262","杭政储出（2023)112地块10号楼1单元803室				"),
("CXAFH-YH-2400263","杭政储出（2023)112地块10号楼1单元804室				"),
("CXAFH-YH-2400264","杭政储出（2023)112地块10号楼1单元903室				"),
("CXAFH-YH-2400265","杭政储出（2023)112地块10号楼1单元904室				"),
("CXAFH-YH-2400266","杭政储出（2023)112地块10号楼1单元1003室				"),
("CXAFH-YH-2400267","杭政储出（2023)112地块10号楼1单元1004室				"),
("CXAFH-YH-2400268","杭政储出（2023)112地块10号楼1单元1103室				"),
("CXAFH-YH-2400269","杭政储出（2023)112地块10号楼1单元1104室				"),
("CXAFH-YH-2400270","杭政储出（2023)112地块10号楼1单元1203室				"),
("CXAFH-YH-2400271","杭政储出（2023)112地块10号楼1单元1204室				"),
("CXAFH-YH-2400272","杭政储出（2023)112地块10号楼1单元1303室				"),
("CXAFH-YH-2400273","杭政储出（2023)112地块10号楼1单元1304室				"),
("CXAFH-YH-2400274","杭政储出（2023)112地块10号楼1单元1403室				"),
("CXAFH-YH-2400275","杭政储出（2023)112地块10号楼1单元1404室				"),
("CXAFH-YH-2400276","杭政储出（2023)112地块10号楼1单元1503室				"),
("CXAFH-YH-2400277","杭政储出（2023)112地块10号楼1单元1504室				"),
("CXAFH-YH-2400278","杭政储出（2023)112地块10号楼1单元1603室				"),
("CXAFH-YH-2400279","杭政储出（2023)112地块10号楼1单元1604室				"),
("CXAFH-YH-2400280","杭政储出（2023)112地块10号楼1单元1703室				"),
("CXAFH-YH-2400281","杭政储出（2023)112地块10号楼1单元1704室				"),
("CXAFH-YH-2400282","杭政储出（2023)112地块10号楼1单元1803室				"),
("CXAFH-YH-2400283","杭政储出（2023)112地块10号楼1单元1804室				"),
("CXAFH-YH-2400284","杭政储出（2023)112地块10号楼1单元1903室				"),
("CXAFH-YH-2400285","杭政储出（2023)112地块10号楼1单元1904室				"),
("CXAFH-YH-2400286","杭政储出（2023)112地块10号楼1单元2003室				"),
("CXAFH-YH-2400287","杭政储出（2023)112地块10号楼1单元2004室				"),
("CXAFH-YH-2400288","杭政储出（2023)112地块10号楼1单元2103室				"),
("CXAFH-YH-2400289","杭政储出（2023)112地块10号楼1单元2104室				"),
("CXAFH-YH-2400290","杭政储出（2023)112地块10号楼1单元2203室				"),
("CXAFH-YH-2400291","杭政储出（2023)112地块10号楼1单元2204室				"),
("CXAFH-YH-2400292","杭政储出（2023)112地块10号楼1单元2303室				"),
("CXAFH-YH-2400293","杭政储出（2023)112地块10号楼1单元2304室				"),
("CXAFH-YH-2400294","杭政储出（2023)112地块10号楼1单元2403室				"),
("CXAFH-YH-2400295","杭政储出（2023)112地块10号楼1单元2404室				"),
("CXAFH-YH-2400296","杭政储出（2023)112地块10号楼1单元2503室				"),
("CXAFH-YH-2400297","杭政储出（2023)112地块10号楼1单元2504室				"),
("CXAFH-YH-2400298","杭政储出（2023)112地块10号楼1单元2603室				"),
("CXAFH-YH-2400299","杭政储出（2023)112地块10号楼1单元2604室				"),
("CXAFH-YH-2400400","杭政储出（2023)112地块1号楼1单元公共部位				"),
("CXAFH-YH-2400401","杭政储出（2023)112地块1号楼2单元公共部位				"),
("CXAFH-YH-2400402","杭政储出（2023)112地块2号楼1单元公共部位				"),
("CXAFH-YH-2400405","杭政储出（2023)112地块8号楼1单元公共部位				"),
        ]):
            print(f"正在修改第{index+1}条：{report[0]}，{report[1].strip()}")
            sn_code = 10309
            result = yida_client.update_form_data_by_field(report_form_uuid,
                                                    admin_user_id,
                                                    search_field=[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report[0]  # 报告编号
                                                        }
                                                    ],
                                                    update_field={
                                                        "textField_lphpacz0":report[1].strip(), #业务员
                                                    })
        pass
    def test_update_data(self):
        # 加载output.json文件
        with open("/Users/xusijiao/Desktop/xiaming_py/reportservice/yida_app_service/chengxiang/resorce/output.json", "r") as f:
            data:list = json.load(f)
            data_arr = [
                ("CXHJ-QJ-2400022"	,"7fef2757-602f-4ff3-9d84-3313786ef5c5"),
                ("CXCF-WC-2400039"	,"5b633dcd-0794-42ab-bcee-1447ff8b5851"),
                ("CXHL-KC-2400144"	,"733c2acc-22e1-43d2-b5e8-18763eb9dc5b"),
            ]
            # test_update_data
            index = 1
            for report_code,order_no in data_arr:
                report = next((order for order in data if order["orderNo"] == order_no), None)
                if report:
                    print(f"正在修改第{index}条:{report_code}")
                    index += 1
                    update_result = yida_client.update_form_data_by_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                          admin_user_id,
                                                          [
                                                              {
                                                                "type": "TEXT",
                                                                "operator": "eq",
                                                                "componentName": "TextField",
                                                                "key": "textField_lp93kxup",
                                                                "value": report_code
                                                              }
                                                          ],
                                                          {
                                                              "textField_ltmlzgdv": json.dumps(report)
                                                          }
                                                          )
                    print(update_result)


    def download_content_report(self):
        reports =[("CX01-010592500010","out-pdf/202503/b1934d4a-79bc-4317-b9f3-f5e87cc3fc1d/content.pdf"),
                  ("CX01-052452500006","out-pdf/202503/6d682a4c-9a53-4be6-a06f-762818076fdb/content.pdf"),
                  ("CXAL-LP-2400117","out-pdf/202407/e95ad9fe-5b7a-4692-8ffd-613f8386a589/content.pdf"),
                  ("CXAL-LP-2400175","out-pdf/202411/2beb5e0e-f820-48ca-bbf7-9dcd624daa9b/content.pdf"),
                  ("CXAL-LP-2400176","out-pdf/202411/3ad72f16-c11e-4399-b28b-e90eb6239753/content.pdf"),
                  ("CXAL-LP-2400177","out-pdf/202411/c2fbacac-1d4f-4dfa-9050-722e2b605d34/content.pdf"),
                  ("CXAL-LP-2400178","out-pdf/202411/e936f86a-bab3-4e4d-ad21-16032b59c124/content.pdf"),
                  ("CXAL-LP-2400179","out-pdf/202411/35aa7095-1f57-4144-9c60-bbcc079f95ab/content.pdf"),
                  ("CXAL-LP-2400180","out-pdf/202411/e838a7cf-ee4e-4ce7-9547-05d4a3447175/content.pdf"),
                  ("CXAL-LP-2400181","out-pdf/202411/e409aeb6-e3d5-4a5d-9064-e8ea6cd0d289/content.pdf"),
                  ("CXAL-LP-2400182","out-pdf/202411/c2bb5f46-63c6-406a-a054-13c2a732fffb/content.pdf"),
                  ("CXAL-LP-2400183","out-pdf/202411/453deb4d-12e9-4546-8abf-654314eab51b/content.pdf"),
                  ("CXAL-LP-2400184","out-pdf/202411/30286a45-a149-4fe9-bb24-8c3dfc1d54c0/content.pdf"),
                  ("CXAL-LP-2400185","out-pdf/202411/1fd7d84c-ce8d-462d-abfe-c97fd9af87a6/content.pdf"),
                  ("CXAL-LP-2400186","out-pdf/202411/58653f65-9257-489a-8892-7291bacb073a/content.pdf"),
                  ("CXAL-LP-2400187","out-pdf/202411/030ea56b-a7e2-4c42-8719-48b3bd80cba4/content.pdf"),
                  ("CXAL-LP-2400188","out-pdf/202411/1ea1429d-9a6e-43da-b0a1-687ef6ac4045/content.pdf"),
                  ("CXAL-LP-2400189","out-pdf/202411/d5408fd5-9e34-45f7-91b2-61373d548aca/content.pdf"),
                  ("CXAL-LP-2400190","out-pdf/202411/0d6a90b1-78de-4b2b-b090-22aaa9d429af/content.pdf"),
                  ("CXAL-LP-2400191","out-pdf/202411/1d1dd74e-22af-44b0-9771-d90c54177764/content.pdf"),
                  ("CXAL-LP-2400192","out-pdf/202411/a2a0cbb2-f775-49b2-9ae7-18d1929ada9c/content.pdf"),
                  ("CXAL-LP-2400206","out-pdf/202411/831b6586-e6b6-45b6-931f-13e9edf2b5a1/content.pdf"),
                  ("CXAL-LP-2400207","out-pdf/202412/fc20e202-db0e-4c4b-a1f9-e06555c03f21/content.pdf"),
                  ("CXAL-LP-2400208","out-pdf/202412/ac20ee78-0d0f-46f1-9123-f9e421b3a63d/content.pdf"),
                  ("CXAL-LP-2400210","out-pdf/202412/ab834071-817a-4db4-b86e-c625b2347edc/content.pdf"),
                  ("CXAL-LP-2400212","out-pdf/202501/39ed902e-ee77-458c-a083-2da53a204cff/content.pdf"),]
        for index,report in enumerate(reports):
            report_code,report_path = report
            bucket.get_object_to_file(report_path,f"/Users/xusijiao/Downloads/nnnn/{report_code}.pdf")

    def test_script(self):
        '''修改报告编号'''
        result = yida_client.update_form_data_by_id("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                    admin_user_id,
                                                    form_inst_id="2790d010-a240-4d0e-9d1a-29adf98282d6",
                                                    update_field={
                                                        "textField_lp93kxup":"CXFL-HY-2400269" #报告编号
                                                    })
    
    def test_archive_id_script(self):
        '''修改归档编号'''
        prefix = "F24"
        code = 1833
        for report in [
            "CXCF-RA-2400017"
        ]:
            print(f"正在修改{report}")
            result = yida_client.update_form_data_by_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                  admin_user_id,
                                                  [
                                                      {
                                                        "type": "TEXT",
                                                        "operator": "eq",
                                                        "componentName": "TextField",
                                                        "key": "textField_lp93kxup",
                                                        "value": report
                                                      }
                                                  ],
                                                  update_field={
                                                        "textField_lvg2c3u6":f"{prefix}{str(code).zfill(5)}",
                                                        "numberField_lvg2c3u5":code
                                                    }
                                                  )
            code += 1
            if result == "success":
                print("修改成功")
            # result = yida_client.update_form_data_by_id("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
            #                                         admin_user_id,
            #                                         form_inst_id="3dda5dd1-362a-4781-954d-d08b104118f3",
            #                                         update_field={
            #                                             "textField_lvg2c3u6":"J2404452",
            #                                             "numberField_lvg2c3u5":4452 #报告编号
            #                                         })

    def test_gen_finicial_list(self):
        name = "吴兴区常溪单元2024"
        '''生成财务清单'''
        report_codes = [
"CXEL-AJ-2400287",
"CXEL-AJ-2400286",
"CXEL-AJ-2400283",
"CXEL-AJ-2400282",
"CXEL-AJ-2400281",
"CXEL-AJ-2400280",
"CXEL-AJ-2400279",
"CXEL-AJ-2400278",
"CXEL-WX-2400083",
"CXEL-WX-2400081",
"CXEL-WX-2400082",
"CXEL-WX-2400077",
"CXEL-WX-2400078",
"CXEL-WX-2400079",
"CXEL-WX-2400080",

        ]
        all_reports = []
        for report_code in report_codes:
            report_res = yida_client.get_form_data_by_search_field(report_form_uuid,admin_user_id,[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report_code
                                                        }
                                                    ])
            if report_res:
                print(f"已找到报告：{report_code}")
                report_form_data = report_res[0].form_data
                report_info = {
                    "报告编号":report_code,
                    "工程名称": report_form_data.get("textField_lphpacz0"),
                    "委托单位":report_form_data.get("textField_lphpacz4"),
                    "样品名称":report_form_data.get("textField_lr0cupsi"),
                    "业务员":report_form_data.get("textField_lqetx3jq"),
                }
                finacial_res = yida_client.get_form_data_by_search_field(finicial_form_uuid,admin_user_id,[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_ltmbnezf",
                                                            "value": report_code
                                                        }
                                                    ])
                if finacial_res:
                    print(f"已找到财务表单：{report_code}")
                    finacial_form_data = finacial_res[0].form_data
                    report_info.update({
                        "总检测金额":finacial_form_data.get("numberField_lv0lyit8")
                    })
                else:
                    print(f"未找到财务表单：{report_code}")
                
                all_reports.append(report_info)
            else:
                print(f"未找到报告：{report_code}")
                all_reports.append({
                    "报告编号":report_code,
                })
        df = pd.DataFrame(all_reports)
        # 导出为Excel文件
        excel_file_path = f"/Users/xusijiao/Desktop/tmp_folder/{name}.xlsx"
        df.to_excel(excel_file_path, index=False, engine='openpyxl')

        print(f"报告清单已成功导出到: {excel_file_path}")

    def test_group_info_script(self):
        '''修改组长组员'''
        bzy_ids = ["362722146421172630","293760243232505015","501310113725972036","296836250826290258","012035271224228189","273464525536237122"] #编制员id
        leader_id = "101430034232123441" # 组长id
        for bzy_id in bzy_ids:
            print(f"正在更新编制员：{bzy_id}")
            res_search,total = yida_client.get_all_form_data_by_search_field(report_form_uuid,
                                                          admin_user_id,
                                                          [{"key":"employeeField_lqwgfnad","value":bzy_id,"type":"STRING","operator":"eq","componentName":"EmployeeField"}])
            print(f"总计：{total}")
            for index,report in enumerate(res_search):
                print(f"正在修改第{index+1}条:{report.form_instance_id}")
                result = yida_client.update_form_data_by_id("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                        admin_user_id,
                                                        form_inst_id=report.form_instance_id,
                                                        update_field={
                                                              "multiSelectField_lqwcqyd1":[
                                                                    bzy_id,
                                                                    leader_id
                                                              ],
                                                              "employeeField_lqwgfnad": [
                                                                    bzy_id,
                                                                    leader_id
                                                              ]
                                                          })
                print(result)
                time.sleep(2)
    
    def test_update_model(self):
        '''修改模版编号'''
        for form_inst_id in [
            "a9d09538-3f94-45de-85df-605fd0f89f05",
            "cc2f41d0-2a50-48b7-bf24-85b8d808ea08",
            "251d6914-6217-41e5-9588-f52ae6d79333",
            "cc9bf6af-fa74-487e-99f8-5f466c0d44ac",
            "d6219900-467f-47a2-ad2f-d03c20dc7dd4",
            "0643fd4b-7995-41d9-961c-45fb8278a883",
        ]:
            result = yida_client.update_form_data_by_id("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                        admin_user_id,
                                                        form_inst_id=form_inst_id,
                                                        update_field={
                                                            "textField_lqbsdaaj":"VVC66HB12V0QT1LPFPTFZ8N6X8CO2ZIS8N23M2", #模版编号
                                                        })
            print(f">>>>>{result}")
    
    def test_update_zg(self):
        '''修改总工'''
        for form_inst_id in [
            "c9359ef8-9ec9-438a-96d8-cf78eeb2479b",
        ]:
            result = yida_client.update_form_data_by_id("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                    admin_user_id,
                                                    form_inst_id=form_inst_id,
                                                    update_field={
                                                        "employeeField_lqkmu48d":["1410641735697591"], #一级总工
                                                        "employeeField_lq4t9qtu":["1410641735697591"], # 三级总工
                                                    })
            print("form_inst_id>>>>",form_inst_id)
    def test_script_1(self):
        '''
        修改材料审核人和三级总工
        李素娇：4302516026430609
        黄国亮：303924331339769365
        '''
        for form_inst_id in [
            "75fc7f3b-cd60-4f83-b1a7-89d85e66f337",
            "f4521df8-9d93-4f78-a00e-5ff9ac7c711a",
        ]:
            result = yida_client.update_form_data_by_id("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                    admin_user_id,
                                                    form_inst_id=form_inst_id,
                                                    update_field={
                                                        "employeeField_lpkl919z":["4302516026430609"], #审核人
                                                        "employeeField_lq4t9qtu":["303924331339769365"], # 三级总工
                                                        "textField_lqbsdaaj":"VBD66H817MCHPX1W9JKFX8KTOGTF2E90F3WQL4O3" # 模版编号
                                                    })
            print("form_inst_id>>>>",form_inst_id)
        pass

    def test_update_sign(self):
        '''更新签名'''
        person_res = yida_client.update_form_data_by_field(person_form_uuid,admin_user_id,[
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "textField_lp0zbal4",
              "value": "024021201326222852"
            }
          ],{
              "digitalSignatureField_lp0tv65b":"https://tianshu-vpc.oss-cn-shanghai.aliyuncs.com/de751d31-2ee5-417e-9829-1fcb863e3dfa.png"
          })
        
        
            
    def test_update_bzy(self):
        '''更新编制员'''
        form_uuid = "FORM-0BC04FECE4F544B297D37901915570D2OEIY"
        person_form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG"
        form_inst_id = "9b49fad1-5311-4bc3-87a4-f1fd6bc4a18b"
        res = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
        form_data = res[0].form_data
        name = form_data.get('textField_lrd6lxm1') # 编制人name
        bzy_select = form_data.get('selectField_lqwcqyd0') #编制员
        bzy_select_id = form_data.get('selectField_lqwcqyd0_id')
        if (not bzy_select_id) or (name == bzy_select):
            return
        person_res = yida_client.get_form_data_by_search_field(person_form_uuid,admin_user_id,[
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "textField_lp0tv654",
              "value": name
            }
          ])
        person_instance = person_res[0].form_data
        person_id = person_instance.get("textField_lp0zbal4")
        if bzy_select_id == person_id:
            return
        else:
            result = yida_client.update_form_data_by_id(form_uuid,admin_user_id,form_inst_id,{
                "selectField_lqwcqyd0":person_id,
            })
        pass

    def test_batch_delete_record(self):
        '''批量删除记录'''
        form_inst_ids = [
            "d2189732-f30e-44ce-bc63-9cce3fba0b5d",
            "0baca832-9d96-4296-a679-ec3e96e1065c",
        ]
        for index,form_inst_id in enumerate(form_inst_ids):
            result = yida_client.delete_form_data(form_inst_id,admin_user_id)
            print(f"第{index}条删除结果>>>>",result)


    def test_recreate_finicial(self):
        '''重新生成财务'''
        report_codes = [
            "CXEM-WX-2400001",
        ]
        for index,report_code in enumerate(report_codes):
            print("正在处理第",index,"条数据")
            form_uuid = "FORM-BAFAA96000BA4C44A0C8F3256EB00407RP4T"
            user_id = "034728252633647035"
            result = yida_client.get_form_data_by_search_field(form_uuid,admin_user_id,[
                {
                  "type": "TEXT",
                  "operator": "eq",
                  "componentName": "TextField",
                  "key": "textField_ltmbnezf",
                  "value": report_code
                }
            ])
            if result and len(result) == 1:
                form_inst_id = result[0].form_instance_id
                del_result = yida_client.delete_form_data(form_inst_id,admin_user_id)
                print("删除结果>>>>",del_result)
            else:
                print("未找到对应数据")
            res = yida_client.get_form_data_by_search_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                      admin_user_id,[
                                                          {
                                                              "type": "TEXT",
                                                              "operator": "eq",
                                                              "componentName": "TextField",
                                                              "key": "textField_lp93kxup",
                                                              "value": report_code
                                                          }
                                                      ])
            res = res[0].form_data
            try:
                amount = int(res.get("textField_lp93kxwq"))
            except:
                amount = 0
            create_result = yida_client.create_process_instance(form_uuid,user_id,{
                "textField_ltmbnezf":report_code,
                "numberField_lv0lyit8":amount,
            },
            "TPROC--HT866U91DJ5KWCDDFPUDJ892JZEX24PYH42VL5")
            print(">>>>>>",create_result)


    def test_update_group_info(self):
        '''更新成员组信息'''
        name = "缪明燕"
        form_uuid = "FORM-861F9E6F4AAE4D73A255247BF7991765XAKG" # 成员表
        report_form_uuid = "FORM-0BC04FECE4F544B297D37901915570D2OEIY" # 报告表
        person_result = yida_client.get_form_data_by_search_field(form_uuid,admin_user_id,[
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "textField_lp0tv654",
              "value": name
            }
        ])
        form_data = person_result[0].form_data
        id = form_data.get("textField_lp0zbal4")
        group_members = form_data.get("multiSelectField_lqwb9ix2_id") + [name+"-"+id]
        for index,member in enumerate(group_members):
            # if member != name+"-"+id: # 编制员不是组长
            #     continue
            if "-" in member:
                member_name = member.split("-")[0]
                member_id = member.split("-")[1]
            else:
                print("未找到对应数据")
                continue
            member_reports,total = yida_client.get_all_form_data_by_search_field(report_form_uuid,admin_user_id,[
                {
                    "type": "TEXT",
                    "operator": "eq",
                    "componentName": "SelectField",
                    "key": "selectField_lqwcqyd0",
                    "value": member_id
                }
            ])
            print(f"共找到{member_name}报告，共计{total}条")
            for report in member_reports:
                form_inst_id = report.form_instance_id
                group_ids:list = report.form_data.get("multiSelectField_lqwcqyd1")
                if id not in group_ids:
                    group_member_ids = [
                                            item.split("-")[1] for item in group_members if "-" in item
                                        ]+[id]
                    update_result = yida_client.update_form_data_by_id(report_form_uuid,
                                                       admin_user_id,
                                                       form_inst_id,{
                                                           "multiSelectField_lqwcqyd1":group_member_ids,
                                                           "employeeField_lqwgfnad": group_member_ids
                                                       })
                    print(f"成功修改{form_inst_id}")

    def test_batch_approve_report(self):
        '''批量审批报告'''
        report_codes = [
            "CXAD-LP-2400004",
        ]
        # for code in range(1123,1413):
        #     report_code = "CXAC-YH-240"+str(code)
        for report_code in report_codes:
            result = yida_client.get_process_data_by_search_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                  admin_user_id,[
                                                      {
                                                        "type": "TEXT",
                                                        "operator": "eq",
                                                        "componentName": "TextField",
                                                        "key": "textField_lp93kxup",
                                                        "value": report_code
                                                      }
                                                  ])
            process_instance_id = result[0].process_instance_id
            history = yida_client.get_approve_history(process_instance_id,"4302516026430609")
            for item in history:
                if item.show_name in ["待审核"]:
                    yida_client.execute_task(process_instance_id,item.task_id,"4302516026430609")
                    time.sleep(3)
            pass
        
    def test_batch_archive_report(self):
            '''批量归档报告'''
            report_codes = [
"CXAF-FY-2408609",
"CXAF-FY-2408610",
"CXAF-FY-2408611",
"CXAF-FY-2408612",
"CXAF-FY-2408613",
"CXAF-FY-2408614",
"CXAF-FY-2408615",
"CXAF-FY-2408616",
"CXAF-FY-2408617",
"CXAF-FY-2408618",
"CXAF-FY-2408619",
"CXAF-FY-2408620",
"CXAF-FY-2408621",
"CXAF-FY-2408622",
            ]
            for index,report_code in enumerate(report_codes):
                print(f"正在归档第{index+1}份：{report_code}")
                # if index < 205:
                #     continue
                result = yida_client.get_process_data_by_search_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                      admin_user_id,[
                                                          {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report_code
                                                          }
                                                      ])
                if not result:
                    print(f"{report_code}未找到流程实例")
                    continue
                process_instance_id = result[0].process_instance_id
                history = yida_client.get_approve_history(process_instance_id,admin_user_id)
                for item in history:
                    if item.show_name in ["待归档"] and item.type == "TODO":
                        gen_sn_url = "https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/gen_serial_number_v2"
                        gdsn_res = requests.post(gen_sn_url,json={
                            "sn_code_field": "textField_lvg2c3u6",
                            "form_uuid": "FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                            "sn_code": "J24",
                            "zfill": "5",
                            "form_inst_id": process_instance_id,
                            "update_sn":False
                        })
                        if gdsn_res.status_code == 200:
                            gdsn_res = gdsn_res.json()
                            if gdsn_res["code"] == 200:
                                sn = gdsn_res["data"]
                                res = yida_client.execute_task(process_instance_id,
                                                        item.task_id,
                                                        item.operator_user_id,
                                                        {
                                                            "textField_lvg2c3u6":sn
                                                        }
                                                        )
                                if not res:
                                    print("fail")
                                    continue
                                if res.status_code == 200:
                                    print("success")
                                pass
                        time.sleep(2)
    def test_batch_upload_pdf(self):
        '''批量替换更新报告'''
        path = "/Users/xusijiao/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/2.0b4.0.9/de60ecca3bc9eead9cb772a7af110542/Message/MessageTemp/bf9701ae66e5493804e99fda550b00b6/File/新建文件夹 (2)"
        file_names = list_pdf_files(path)
        for index,file_name in enumerate(file_names):
            print("正在处理第",index,"条数据")
            file_path = os.path.join(path,file_name)
            report_code = file_name.split(".")[0]
            res = yida_client.get_form_data_by_search_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                      admin_user_id,[
                                                          {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_lp93kxup",
                                                            "value": report_code
                                                          }
                                                      ]
            )
            if res:
                form_inst_id = res[0].form_instance_id
                object_key = f"yida-app/chengxiang/report_origin/{file_name}"
                bucket.put_object_from_file(object_key,file_path)
                xm_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{object_key}"
                result = yida_client.update_form_data_by_id("FORM-0BC04FECE4F544B297D37901915570D2OEIY",admin_user_id,form_inst_id,{
                    "attachmentField_lqrz4ehj":[
                          {
                          "downloadUrl": xm_url,
                          "name": file_name,
                          "previewUrl": xm_url,
                          "url": xm_url,
                          "ext": "pdf"
                          }
                      ]
                })
                print(">>>>>>",result)
            else:
                print("未找到对应数据")
                continue
    def test_correct_bzy(self):
        '''修正编制员和编制人name'''
        name = "陈东"
        user_id = "04396438451212628"
        yida_client = YidaClient()
        result = yida_client.get_form_data_by_search_field("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                  admin_user_id,
                                                  [
                                                      {
                                                        "type": "TEXT",
                                                        "operator": "ne",
                                                        "componentName": "TextField",
                                                        "key": "textField_lrd6lxm1",
                                                        "value": name
                                                      },
                                                      {
                                                        "type": "ARRAY",
                                                        "operator": "eq",
                                                        "componentName": "SelectField",
                                                        "key": "selectField_lqwcqyd0",
                                                        "value": user_id
                                                      },
                                                  ],
                                                  page_size=100,
                                                  start_time="2024-09-01")
        for report in result:
            bzy_name = report.form_data.get("textField_lrd6lxm1")
            print(bzy_name)
            if bzy_name != name:
                print("正在修正>>>",report.form_instance_id)
                person_res = yida_client.get_form_data_by_search_field("FORM-861F9E6F4AAE4D73A255247BF7991765XAKG",admin_user_id,[
                      {
                        "type": "TEXT",
                        "operator": "eq",
                        "componentName": "TextField",
                        "key": "textField_lp0tv654",
                        "value": bzy_name
                      }
                    ])
                person_instance = person_res[0].form_data
                person_id = person_instance.get("textField_lp0zbal4")
                update_res = yida_client.update_form_data_by_id("FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                                                   admin_user_id,
                                                   report.form_instance_id,
                                                   {
                                                        "selectField_lqwcqyd0":person_id
                                                   })
                print(update_res)
        pass

    def test_digital_sign_add_record(self):
        '''电子签章插队'''
        records = [
"0822f491-8cfc-458e-9e61-a9768d303dc4",
"590b144b-6292-4d0e-a4ec-e835b7da9830",

        ]

        # 将多条记录推送到列表中
        try:
            for record in records:
                # 删除列表中所有与 record 相同的元素
                client.lrem('xmDigitalSignTask', 0, record)
            client.rpush('xmDigitalSignTask', *records)
            print("记录成功推送到 xmDigitalSignTask 列表中")
        except Exception as e:
            print(f"发生错误: {e}")

    def test_batch_create_sign_order(self):
        '''批量发起签署'''
        report_codes = [
  "CXLC-DH-2400431",
  "CXLC-DH-2400432",
  "CXLC-DH-2400433",
  "CXLC-DH-2400434",
  "CXLC-DH-2400435",
  "CXLC-DH-2400436",
  "CXLC-DH-2400437",
  "CXLC-DH-2400438",
        ]
        for report_code in report_codes:
            print(f"{report_code}正在发起签署...")
            result = yida_client.get_ids_by_search_field(
                report_form_uuid,
                admin_user_id,
                [
                    {
                      "type": "TEXT",
                      "operator": "eq",
                      "componentName": "TextField",
                      "key": "textField_lp93kxup",
                      "value": report_code
                    }
                ]
            )
            form_inst_id = result[0]
            res = requests.post("https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/create_digital_sign_order",json={
                "form_inst_ids": [form_inst_id]
            })
            if res.status_code == 200:
                print("success")
    
    def copy_process_data(self):
        '''复制流程'''
        form_inst_ids = [
            "9d36fdcc-1e0d-4695-840d-d864a8b18f39",
        ]
        form_uuid = "FORM-0BC04FECE4F544B297D37901915570D2OEIY"
        for index,form_inst_id in enumerate(form_inst_ids):
            print(f"正在复制第{index}份>>>")
            result = yida_client.get_form_items_by_ids(form_uuid=form_uuid,
                                          form_inst_id=form_inst_id,
                                          userId=yida_client.admin_user_id)
            if not result:
                continue
            form_data = result[0].form_data
            creator = result[0].creator_user_id
            new_form_data = {}
            for key in form_data:
                if key.startswith("associationFormField"):
                    asso_key = key[:-3]
                    asso_val = json.loads(json.loads(form_data[key]))
                    new_form_data[asso_key] = asso_val
                elif key.endswith("_id"):
                    continue
                elif key.startswith("selectField"):
                    new_form_data[key] = form_data[key+"_id"]
                elif key.startswith("checkboxField"):
                    new_form_data[key] = form_data[key+"_id"]
                elif key.startswith("radioField"):
                    new_form_data[key] = form_data[key+"_id"]
                elif key.startswith("multiSelectField"):
                    new_form_data[key] = form_data[key+"_id"]
                elif key.startswith("employeeField"):
                    new_form_data[key] = form_data[key+"_id"]
                else:
                    new_form_data[key] = form_data[key]
            result = yida_client.create_process_instance(form_uuid=form_uuid,
                                        userId=creator,
                                        formDataJson=new_form_data,
                                        process_code="TPROC--U0A66091AZQGSDPIFBEQP8HN89KL39DYDE7QLO7")
            # 打开文件（如果文件不存在则会创建一个新文件）
            with open('/Users/xusijiao/Desktop/黄教授/aaa/1021.txt', 'a', encoding='utf-8') as file:
                # 写入要追加的字符串
                file.write(f'{result}\n')
            print(result)

    def alter_reportcode_batch(self):
        '''批量修复报告编号'''
        form_uuid = "FORM-0BC04FECE4F544B297D37901915570D2OEIY"
        form_inst_ids = [
            "02111248-b1d4-4d07-9fa5-2a21be5d0e50",
        ]
        for form_inst_id in form_inst_ids:
            result = yida_client.get_form_items_by_ids(form_uuid=form_uuid,
                                          form_inst_id=form_inst_id,
                                          userId=yida_client.admin_user_id)
            report_code = result[0].form_data.get("textField_lp93kxup")
            if(bool(re.search(r'\d{10}$', report_code))):
                new_report_code = report_code[:-5]
                print(new_report_code)
                result = yida_client.update_form_data_by_id(form_uuid=form_uuid,
                                          form_inst_id=form_inst_id,
                                          userId=yida_client.admin_user_id,
                                          update_field={
                                              "textField_lp93kxup":new_report_code,
                                          })
                print(result)
            else:
                print("格式不正确")

    def delete_report_batch(self):
        form_inst_ids = [
            "9d36fdcc-1e0d-4695-840d-d864a8b18f39",
        ]
        for form_inst_id in form_inst_ids:
            result = yida_client.delete_form_data(form_instance_id=form_inst_id,
                                                  userId=yida_client.admin_user_id)
            print(result)
      
    def update_area(self):
        '''修复地区'''
        form_uuid = "FORM-0BC04FECE4F544B297D37901915570D2OEIY"
        for form_inst_id in [
"b69b27cd-7593-4269-94dc-5b87aaa50f6b",
"8006d688-d954-4b6c-bfa6-ee5e5bab3c2a",
"c6864de3-dadd-4325-88e7-e72cb731c156",
"7099a56e-0bc9-4e95-afa7-66bb20beb441",
"1592fee1-a5e8-47fe-a2fb-69a2770876b0",
"f4392f55-8dde-492c-9230-9cb72d40e689",
        ]:
            result = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,admin_user_id)
            if not result:
                continue
            form_data = result[0].form_data
            report_code = form_data.get("textField_lp93kxup")
            print(report_code)
            sn_1 = report_code[2]
            sn_2 = f"ZJ_{sn_1}_{report_code[5:7]}"
            print(sn_2)
            result = yida_client.update_form_data_by_id(form_uuid,admin_user_id,form_inst_id,{
                # "cascadeSelectField_lpgahbwq":area_id
                "cascadeSelectField_lpgahbwq":[
                    "ZJ",
                    sn_1,
                    sn_2
                ]
            })
            pass
        
    def update_bzy_by_upload_report(self):
      # 更新代写报告人为编制员
        # process_inst_ids = []
        # page = 1
        # page_size = 100
        # batch_size = 1000
        # batch_count = 7
        # while True:
        #     results,total = yida_client.get_process_ids_by_search_field(report_form_uuid,
        #                                                                 admin_user_id,
        #                                                                 "2024-05-01",
        #                                                                 "2024-10-01",
        #                                                                 page=page)
        #     process_inst_ids += results
        #     if len(process_inst_ids) >= batch_size:
        #         batch_data = process_inst_ids[:batch_size]
        #         process_inst_ids = process_inst_ids[batch_size:]  # 剩余的未保存数据

        #         # 创建一个新的工作簿
        #         wb = openpyxl.Workbook()
        #         ws = wb.active
        #         ws.title = f"Batch {batch_count}"

        #         # 将批量数据写入Excel
        #         for idx, process_inst_id in enumerate(batch_data, start=1):
        #             ws[f"A{idx}"] = process_inst_id

        #         # 保存到文件
        #         output_file = f"/Users/xusijiao/Downloads/aaap/process_{batch_count}.xlsx"
        #         wb.save(output_file)
        #         print(f"第{batch_count}批数据已保存到 {output_file}")

        #         # 更新批次号
        #         batch_count += 1
        #     if((page) * page_size >= total):
        #         break
        #     page += 1
        # print(f"获取到{total}条数据")
        # if process_inst_ids:
        #     wb = openpyxl.Workbook()
        #     ws = wb.active
        #     ws.title = f"Batch {batch_count}"

        #     # 将剩余的数据写入Excel
        #     for idx, process_inst_id in enumerate(process_inst_ids, start=1):
        #         ws[f"A{idx}"] = process_inst_id

        #     # 保存到文件
        #     output_file = f"/Users/xusijiao/Downloads/aaap/process_{batch_count}.xlsx"
        #     wb.save(output_file)
        #     print(f"第{batch_count}批数据已保存到 {output_file}")
        file_dir = f"/root/xm-detection-service/yida_app_service/chengxiang/resorce/tmp/"
        for batch_index in range(27,28):
            file_path = f"{file_dir}process_{batch_index}.xlsx"
            logging.info(f"正在处理第{batch_index}批...")
            wb = openpyxl.load_workbook(file_path)
            ws = wb.active
            process_inst_ids = []
            for row in ws.iter_rows(min_row=1, max_col=1, values_only=True):
                process_inst_ids.append(row[0])
            for index,process_inst_id in enumerate(process_inst_ids, start=1):
                # if index < 530:
                #     continue
                history_data = yida_client.get_approve_history(process_inst_id,admin_user_id)
                target_node = next((item for item in reversed(history_data) if (item.show_name == "待写报告" and item.action_exit == "agree")), None)
                if target_node:
                    bzy_id = target_node.operator_user_id
                    bzy_name = target_node.operator_name
                    form_data = yida_client.get_process_instance_by_id(admin_user_id,process_inst_id)
                    report_code = form_data.get("textField_lp93kxup")
                    logging.info(f"正在处理第{index+1}条数据,编号：{report_code}")
                    origin_bzy_id = form_data.get("selectField_lqwcqyd0_id")
                    if not bzy_id:
                        # raise Exception("数据异常，请检查数据")
                        continue
                    if bzy_id != origin_bzy_id:
                        res = yida_client.update_form_data_by_field(report_form_uuid,
                                                              admin_user_id,
                                                              [
                                                                  {
                                                                    "type": "TEXT",
                                                                    "operator": "eq",
                                                                    "componentName": "TextField",
                                                                    "key": "textField_lp93kxup",
                                                                    "value": report_code
                                                                  }
                                                              ],
                                                              {
                                                                  "selectField_lqwcqyd0":bzy_id,
                                                                  "employeeField_m1k1eva6":[bzy_id],
                                                                  "textField_lrd6lxm1":bzy_name
                                                              })
                        logging.info(res)
                    else:
                        logging.info("无需处理")
                    
            pass
        
    def update_finicial_bzy_info(self):
        bzy_id = "132058133925879495"
        person = yida_client.get_form_data_by_search_field(person_form_uuid,
                                                           admin_user_id,
                                                           [
                                                               {
                                                               "type": "TEXT",
                                                               "operator": "eq",
                                                               "componentName": "TextField",
                                                               "key": "textField_lp0zbal4",
                                                               "value": bzy_id
                                                           }
                                                           ])
        if not person:
            raise Exception("数据异常，请检查数据")
        else:
            bzy_name = person[0].form_data.get("textField_lp0tv654")
        results,total = yida_client.get_all_form_data_by_search_field(report_form_uuid,admin_user_id,[
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "selectField_lqwcqyd0",
              "value": bzy_id
            },
        ])
        print(f"共计{total}条数据")
        for index,report_inst in enumerate(results):
            if index < 228:
                continue
            report_code = report_inst.form_data.get("textField_lp93kxup")
            sign_date = report_inst.form_data.get("dateField_lp92f309")
            print(f"正在处理第{index+1}条数据，编号：{report_code}")
            finicial_data = yida_client.get_form_data_by_search_field(finicial_form_uuid,
                                                      admin_user_id,
                                                      [
                                                          {
                                                              "type": "TEXT",
                                                              "operator": "eq",
                                                              "componentName": "TextField",
                                                              "key": "textField_ltmbnezf",
                                                              "value": report_code
                                                          }
                                                      ])
            if(len(finicial_data)>1):
                raise Exception("数据异常，请检查数据")
            elif len(finicial_data)==1:
                finicial_form_inst_id = finicial_data[0].form_instance_id
                res = yida_client.update_form_data_by_id(finicial_form_uuid,
                                                   admin_user_id,
                                                   finicial_form_inst_id,
                                                   {
                                                       "textField_lv0ntlyv":bzy_name,
                                                       "textField_m4j9xdl0":bzy_id,
                                                       "dateField_lv0uftfc":sign_date
                                                   })
                print(res)

        pass
    
    def copy_report_attachment_to_xujf(self):
        import oss2
        auth = oss2.Auth("LTAI5t6uQ1q8XbgYHwVBG7k9", "Q0bBMa76xxGEE2pC6US6ifYDUc5tX7")
        xm_bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'xiaming-report',
                            connect_timeout=30)
        for key in [
"out-pdf/202412/6011b55a-51ec-4250-8a07-81d286ec0206",
"out-pdf/202412/0c093df5-b809-4675-8d83-13b26cb87689",
"out-pdf/202412/f20a88bc-2924-4c47-92d5-4c6d3fbf1967",
"out-pdf/202412/4588752d-030d-409f-9f2c-8fa36e82fc3a",
"out-pdf/202412/fca91a25-88a5-4495-84f3-d41712cf8eda",
"out-pdf/202412/5a7916aa-403a-465f-8c8e-ed2f7f083563",
"out-pdf/202412/e3850560-2a37-49f8-adfc-3eab14be564f",
"out-pdf/202412/fc3f5091-b549-4770-86ef-9afbd83621d7",

        ]:
            obj_res = xm_bucket.list_objects(key)
            objs = obj_res.object_list
            for obj in objs:
                obj_key = obj.key
                local_path = f"/Users/xusijiao/Downloads/qy/{obj_key}"
                if not os.path.exists(local_path):
                    os.makedirs(os.path.dirname(local_path), exist_ok=True)
                res = xm_bucket.get_object_to_file(obj_key,local_path)
                pass
    def archive_sign_data_to_xujf_com(self):
        import oss2
        auth = oss2.Auth("LTAI5t6uQ1q8XbgYHwVBG7k9", "Q0bBMa76xxGEE2pC6US6ifYDUc5tX7")
        cname = 'https://sign.zjxmyq.cn'
        xm_bucket = oss2.Bucket(auth, cname, 'xiaming-digitalsign',
                            is_cname=True, connect_timeout=30)
        objects = oss2.ObjectIteratorV2(xm_bucket)
        for index,obj in enumerate(objects):
            obj_key:str = obj.key
            if index < 45914:
                continue
            logging.info(f"正在迁移第{index + 1}份:{obj_key}")
            try:
                download_url = xm_bucket.sign_url('GET', obj_key, 3600)
                with requests.get(download_url) as response:
                    cover_content = response.content
                    ds_bucket.put_object(obj_key, cover_content)
                    logging.info("success")
            except Exception as e:
                with open('test_error.txt', 'a') as f:
                    logging.error(f"{obj_key}迁移失败")
                    f.write(f"{obj_key}\n")
    def cache_finacial_data(self):
        '''缓存财务数据'''
        times_ranges = [
            ("2024-01-01","2024-02-01"),
            ("2024-02-01","2024-03-01"),
            ("2024-03-01","2024-04-01"),
            ("2024-04-01","2024-04-15"),
            ("2024-04-15","2024-05-01"),
            ("2024-05-01","2024-06-01"),
            ("2024-06-01","2024-07-01"),
            ("2024-07-01","2024-08-01"),
            ("2024-08-01","2024-09-01"),
            ("2024-09-01","2024-10-01"),
            ("2024-10-01","2024-11-01"),
            ("2024-11-01","2024-12-01"),
            ("2024-12-01","2025-01-01"),
        ]
        for batch_index,time_range in enumerate(times_ranges):
            print(f"正在缓存{time_range[0]}到{time_range[1]}的数据")
            results,total = yida_client.get_all_form_data_by_search_field(finicial_form_uuid,admin_user_id,[
                { "key": "currentNodeName", "value": ["结清"], "type": "ARRAY", "operator": "contains", "componentName": "TextField" },
            ],
                                                                      create_from_time_gmt=time_range[0],
                                                                      create_to_time_gmt=time_range[1])
            for index, result in enumerate(results):
                form_data = result.form_data
                value_obj = {
                    "form_data": form_data,
                    "form_instance_id":result.form_instance_id,
                    "process_status":"结清",

                }
                print(f"正在处理第{batch_index}组第{index}份报告：{form_data.get('textField_ltmbnezf')}")
                value = json.dumps(value_obj,skipkeys=True)
                key = f"chengxiang:form_data:{finicial_form_uuid}:{form_data.get('textField_ltmbnezf')}"
                cache.set(key,value,timeout=None)
        return "success"
    
    def download_fake_report_pdf(self):
        '''批量下载无章报告'''
        save_path = "/Users/xusijiao/Desktop/tmp_folder/report_out"
        report_codes = [
"CXHL-LY-2400083",
"CXHL-LY-2400084",
"CXHL-LY-2400085",
"CXHL-LY-2400086",
"CXHL-LY-2400087",
"CXHL-LY-2400088",
"CXHL-LY-2400089",
"CXHL-LY-2400090",
"CXHL-LY-2400091",
"CXHL-LY-2400112",
"CXHL-LY-2400113",
"CXHL-LY-2400114",
"CXHM-LY-2400005",
        ]
        for index,report_code in enumerate(report_codes):
            print(f"正在下载{report_code}...")
            result = requests.get(f"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/get_fake_sign_report?reportCode={report_code}")
            if result.status_code == 200:
                res_data = json.loads(result.text)
                down_url = res_data.get("data")
                if not down_url:
                    print("down_url is None")
                    continue
                down_res = requests.get(down_url)
                if down_res.status_code == 200:
                    file_content = down_res.content
                    with open(f"{save_path}/{report_code}.pdf", "wb") as file:
                        file.write(file_content)
                        print("success")
    def download_report_pdf(self):
        '''批量下载已签署的报告'''
        save_path = "/Users/xusijiao/Desktop/tmp_folder/report_out"
        report_codes = [
"CXKL-QY-2400024",
"CXKL-QY-2400025",
"CXLL-SS-2400040",
"CXLL-SS-2400041",
"CXHM-JS-2400001",
"CXHM-JS-2400002",
"CXHM-JS-2400003",
"CXHM-JS-2400004",
        ]
        for index,report_code in enumerate(report_codes):
            # if index <= 172:
            #     continue
            print(f"正在下载{report_code}...")
            result = requests.get(f"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/get_whole_report?reportCode={report_code}")
            if result.status_code == 200:
                res_data = json.loads(result.text)
                down_url = res_data.get("data")
                if not down_url:
                    print("down_url is None")
                    continue
                down_res = requests.get(down_url)
                if down_res.status_code == 200:
                    file_content = down_res.content
                    with open(f"{save_path}/{report_code}.pdf", "wb") as file:
                        file.write(file_content)
                        print("success")


                        
    def batch_gen_report_code(self):
        file_path = "/Users/xusijiao/Downloads/项目信息-流程_20241231173509.xlsx"
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        process_inst_ids = []
        for row in ws.iter_rows(min_row=2, max_col=1, values_only=True):
            process_inst_ids.append(row[0])
        for form_inst_id in process_inst_ids:
            res = requests.post("https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/gen_serial_number_v2",json={
                "form_uuid": "FORM-0BC04FECE4F544B297D37901915570D2OEIY",
                "sn_code": "CXAF-LP-24",
                "sn_code_field": "textField_lp93kxup",
                "zfill": 5,
                "form_inst_id":form_inst_id
            })
            if res.status_code == 200:
                print("success")
    
    def async_finacial_data(self):
        '''同步财务状态'''
        report_codes = [
"CXAL-LP-2400006",
"CXAL-LP-2400007",
        ]
        for index,report_code in enumerate(report_codes):
            print(f"正在处理第{index}条：{report_code}")
            results = yida_client.get_process_data_by_search_field(finicial_form_uuid,
                                                      admin_user_id,
                                                      search_field=[
                                                        {
                                                            "type": "TEXT",
                                                            "operator": "eq",
                                                            "componentName": "TextField",
                                                            "key": "textField_ltmbnezf",
                                                            "value": report_code
                                                        }
                                                      ])
            process_instance_id = results[0].process_instance_id
            historys = yida_client.get_approve_history(process_instance_id,admin_user_id)
            for history in historys:
                if history.type == "TODO":
                    res = yida_client.update_form_data_by_field(report_form_uuid,
                                                          admin_user_id,
                                                          [
                                                            {
                                                                "type": "TEXT",
                                                                "operator": "eq",
                                                                "componentName": "TextField",
                                                                "key": "textField_lp93kxup",
                                                                "value": report_code
                                                            }
                                                          ],
                                                          {
                                                              "selectField_ltphfd90":history.show_name
                                                          })
                    print(res)
                    break

    def update_report_items(self):
        form_inst_ids = [
          "c1039bbf-f643-46df-9931-439ff2c5fd4f"
        ]
        for form_inst_id in form_inst_ids:
            res = yida_client.get_form_items_by_ids(
                report_form_uuid,
                form_inst_id,
                admin_user_id
            )
            sample_name = res[0].form_data["associationFormField_m5fr6hbc"]
            yida_client.update_form_data_by_id(
                "FORM-ECA0610E2D22462E8E7C3D2D6698E69F84TV",
                admin_user_id,
                form_inst_id,
                {
                    # "cascadeSelectField_m57uzjbv":["检测"]
                    "textField_m3y83bfq":"项目21"
                }
            )
    def create_report_items(self):
        result = yida_client.create_form_data(
            "FORM-ECA0610E2D22462E8E7C3D2D6698E69F84TV",
            admin_user_id,
            {
                "selectField_m5fq21f7":"测试类型",
                "selectField_m5fq21fd":"子类型1",
                "textField_m3y83bfq":"项目1",
                "textField_m57uzjbw":"test01"
            }
        )
        pass
    
    def batch_gen_download_file(self):
        '''批量下载文件'''
        save_path = "/Users/xusijiao/Downloads/sss"
        file_path = "/Users/xusijiao/Downloads/检测设备信息_20250301163148.xlsx"
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        for index,row in enumerate(ws.iter_rows(min_row=3, max_col=2, values_only=True)):
            print(f"正在生成：{row[0]}...")
            url = rf"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang/print_form_data/185?form_instance_id={row[1]}&form_uuid=FORM-BFDC1A4B9F7D4DB282EF7EE33851F9168NP3"
            res = requests.get(url)
            if res.status_code == 200:
                file_content = res.content
                with open(f"{save_path}/{row[0]}_{index}.pdf", "wb") as file:
                    file.write(file_content)
                    print("success")
            
    def batch_gen_pjb_pdf_by_model(self):
        '''批量生成校准评价表'''
        model_id = 472
        save_path = "/Users/xusijiao/Downloads/sss"
        file_path = f"/Users/xusijiao/Downloads/临平CX01-635-673设备莱博广东校准评价表2025.03.01.xlsx"
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        for index,row in enumerate(ws.iter_rows(min_row=2, max_col=12, values_only=True)):
            print(f"正在生成：{row[0]}...")
            params = {
                "textField_lyyku9br":row[0],
                "textField_lyr7iny6":row[1],
                "numberField_lyyku9bp":row[2],
                "textField_lyr7iny7":row[3],
                "textField_m5m3xbd0":row[4],
                "textField_m5m3xbd1":row[5],
                "dateField_lz97ci5n":row[6].timestamp(),
                "dateField_m5m3xbd2":row[7].timestamp(),
                "textField_m5m3xbd3":row[8],
                "dateField_m5m3xbd5":row[9].timestamp(),
                "dateField_m5m3xbdf":row[10].timestamp(),
                "dateField_m5m3xbdg":row[11].timestamp(),
            }
            result = xm_client.render_model(model_id,params)
            download_url = result.get("data").get("download_url")
            down_res = requests.get(download_url)
            if down_res.status_code == 200:
                file_content = down_res.content
                with open(f"{save_path}/{str(index+2).zfill(4)}.pdf", "wb") as file:
                    file.write(file_content)
                    print("success")
          
    def batch_gen_ysd_pdf_by_model(self):
        '''批量生成验收表'''
        model_id = 218
        save_path = "/Users/xusijiao/Downloads/sss"
        file_path = f"/Users/xusijiao/Downloads/临平635-673验收基本信息表2025.03.01.xlsx"
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        for index,row in enumerate(ws.iter_rows(min_row=2, max_col=12, values_only=True)):
            print(f"正在生成：{row[0]}...")
            params = {
                "textField_lyxrtwkw":row[0],
                "textField_lyyj1yzn":row[1],
                "textField_lyyj1yzg":row[2],
                "textField_lrcutqa0":row[3],
                "dateField_lywqwe7u":row[4].timestamp(),
            }
            result = xm_client.render_model(model_id,params)
            download_url = result.get("data").get("download_url")
            down_res = requests.get(download_url)
            if down_res.status_code == 200:
                file_content = down_res.content
                with open(f"{save_path}/{str(index+2).zfill(4)}.pdf", "wb") as file:
                    file.write(file_content)
                    print("success")

    def batch_gen_sgb_pdf_by_model(self):
        '''批量生成申购表'''
        model_id = 204
        save_path = "/Users/xusijiao/Downloads/sss"
        file_path = f"/Users/xusijiao/Downloads/临平购置时间表薛朝芹.xlsx"
        wb = openpyxl.load_workbook(file_path)
        ws = wb.active
        for index,row in enumerate(ws.iter_rows(min_row=2, max_col=12, values_only=True)):
            print(f"正在生成：{row[0]}...")
            # if index < 73:
            #     continue
            params = {
                "textField_lyf8awh8":row[1],
                "textField_ly6nmp7f":row[2],
                "textField_ly6nmp7g":row[3],
                "numberField_lyx2osok":row[4],
                "date_1":row[5].timestamp(),
                "date_2":row[6].timestamp(),
                "date_3":row[7].timestamp(),
                "date_4":row[8].timestamp(),
            }
            result = xm_client.render_model(model_id,params)
            download_url = result.get("data").get("download_url")
            down_res = requests.get(download_url)
            if down_res.status_code == 200:
                file_content = down_res.content
                with open(f"{save_path}/{str(row[0]).zfill(4)}.pdf", "wb") as file:
                    file.write(file_content)
                    print("success")

    def add_bak_task(self):
        bak_xlxs_file = "/Users/xusijiao/Downloads/bak24_0501-0715.xlsx"
        wb = openpyxl.load_workbook(bak_xlxs_file)
        ws = wb.active
        key = "bak24_task"
        for index,row in enumerate(ws.iter_rows(min_row=2, max_col=2, values_only=True)):
            report_code = row[1]
            form_inst_id = row[0]
            task_id = f"{report_code}$${form_inst_id}"
            bak_r.rpush(key, task_id)

        
    def bak_to_xu_cloud(self):
        key = "bak24_task"
        fiail_key = "bak24_task_fail"
        while task_id := bak_r.lpop(key):
            report_code = task_id.split("$$")[0]
            form_inst_id = task_id.split("$$")[1]
            print(f"正在备份：{report_code}...")
            try:
                res = yida_client.get_form_items_by_ids(report_form_uuid,form_inst_id,admin_user_id)
                if res:
                    form_data = res[0].form_data
                    creator = res[0].creator_user_id
                    histories = yida_client.get_approve_history(form_inst_id,admin_user_id)
                    processes = {
                        "start_time":res[0].create_time_gmt,
                        "process_inst_id":form_inst_id,
                        "tasks":[
                            {
                                "task_definition_key":history.show_name,
                                "assignee":history.operator_user_id,
                                "startTime":history.active_time_gmt,
                                "endTime":history.operate_time_gmt,
                            } for history in histories
                        ]
                    }
                    params = {
                        "form_data":form_data,
                        "creator":creator,
                        "processes":processes,
                        "created_at":res[0].create_time_gmt
                    }
                    report = Report.objects.filter(report_code=report_code).last()
                    if report:
                        if report.digital_sign_order_no:
                            params["digital_sign_order_no"] = report.digital_sign_order_no
                    
                    api = "https://api.zjcxjc.cn/api/v0/xu-cloud/chengxiang-report/import-report-2024/"
                    result = requests.post(api,json=clean_dict(params),headers={
                        "Content-Type":"application/json",
                        "Authorization":"Token a2f835ece0c1ea5384ae5422829c5f9d35d0aca0"
                    })
                    if(result.status_code != 200):
                        print("备份失败，加入失败队列")
                        bak_r.rpush(fiail_key,task_id)
                    else:
                        print("备份成功")
            except Exception as e:
                bak_r.rpush(fiail_key,task_id)
                print(e)
                continue

def clean_dict(d):
    return {
        k: v for k, v in d.items() 
        if v is not None and v != '' and not (isinstance(v, list) and len(v) == 0)
    }

    
def list_pdf_files(directory):
    paths = []
    # 遍历指定目录下的所有文件
    for filename in os.listdir(directory):
        # 检查文件是否为 PDF 文件
        if filename.endswith('.pdf'):
            print(filename)
            paths.append(filename)
    return paths

def start_backup_task_test(form_instance,form_uuid):
    
    logger.info(f"正在处理报告：{form_instance.form_data.get('textField_lp93kxup')}")
    try:
        report = Report.objects.get(report_code=form_instance.form_data.get('textField_lp93kxup'))
    except Report.DoesNotExist:
        logger.info(f"未找到报告：{form_instance.form_data.get('textField_lp93kxup')}")
        report = None
    except Report.MultipleObjectsReturned:
        logger.info(f"找到多个报告：{form_instance.form_data.get('textField_lp93kxup')}")
        reports = Report.objects.filter(report_code=form_instance.form_data.get('textField_lp93kxup')).order_by('-created_at')
        if reports.exists():
            report = reports.first()
            logger.info(f"找到多个报告，取最新报告：{report}")
        else:
            logger.info(f"未找到报告：{form_instance.form_data.get('textField_lp93kxup')}")
    except Exception as e:
        logger.info(f"处理报告时发生错误：{e}")
    if report:
        report_path = report.report_path
    else:
        report_path = f"tmp-out-pdf/{datetime.now().strftime('%Y%m%d')}/{uuid.uuid4()}"
    try:
        bak_attachment(form_instance,"attachmentField_lpb2cdkb",report_path,form_uuid)
        bak_attachment(form_instance,"attachmentField_lpb2cdka",report_path,form_uuid)
        bak_attachment(form_instance,"attachmentField_lpb2cdkd",report_path,form_uuid)
        bak_attachment(form_instance,"attachmentField_lpb2cdkf",report_path,form_uuid)
        bak_attachment(form_instance,"attachmentField_lqrz4ehj",report_path,form_uuid)
        if report:
            whole_path = f"{report_path}/whole.pdf"
            cover_docx_path = f"{report_path}/cover.docx"
            cover_path = f"{report_path}/cover.pdf"
            sign_path = f"{report_path}/sign.pdf"
            content_path = f"{report_path}/content.pdf"
            bak_report_attachement(whole_path)
            bak_report_attachement(cover_docx_path)
            bak_report_attachement(cover_path)
            bak_report_attachement(sign_path)
            bak_report_attachement(content_path)
    except Exception as e:
        logger.info(f"未知错误：{e}")
        record_log(form_instance.form_instance_id)
    yida_client.update_form_data_by_id(report_form_uuid,
                                        admin_user_id,
                                        form_instance.form_instance_id,
                                        {
                                            "selectField_m4wf9ayu":"是"
                                        })
    logger.info("迁移备份成功")
    time.sleep(3)

import oss2
auth = oss2.Auth("LTAI5t6uQ1q8XbgYHwVBG7k9", "Q0bBMa76xxGEE2pC6US6ifYDUc5tX7")
cname = 'https://doc.zjxmyq.cn'
xm_bucket = oss2.Bucket(auth, cname, 'xiaming-report',
                    is_cname=True, connect_timeout=30)
    
def bak_report_attachement(oss_key):
    ex_xu = bucket.object_exists(oss_key)
    ex_xm = xm_bucket.object_exists(oss_key)
    if (not ex_xu) and ex_xm:
        logger.info("开始备份报告附件")
        download_url = xm_bucket.sign_url('GET', oss_key, 3600)
        response = requests.get(download_url)
        if response.status_code == 200:
            file_content = response.content
            bucket.put_object(oss_key, file_content)
    else:
        logger.info("报告附件已存在")

def bak_attachment(form_inst_data,field_name,report_path,form_uuid,retry=3):
    '''备份附件'''
    try:
        logger.info("备份地址"+report_path)
        if field_name not in form_inst_data.form_data:
            logger.info(f"{field_name}该字段无值")
            return
        attachments = json.loads(form_inst_data.form_data[field_name])
        new_attachments = []
        for index,attachment in enumerate(attachments):
            download_url:str = attachment.get("downloadUrl")
            if download_url.startswith("https://api.zjxmyq.cn"):
                oss_key = download_url.replace("https://api.zjxmyq.cn/api/v1/yida-app/common/download_file/","")
                exist = bucket.object_exists(oss_key)
                if exist:
                    xm_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_key}"
                    new_attachment = {
                            "downloadUrl": xm_url,
                            "name": attachment.get('name'),
                            "previewUrl": xm_url,
                            "url": xm_url,
                            "ext": attachment.get('name').split('.')[-1]
                        }
                    logger.info(f"{field_name}已备份已迁移，修改链接中")
                    new_attachments.append(new_attachment)
                    continue
                else:
                    logger.info(f"{field_name}已备份正在迁移")
            elif download_url.startswith("https://api.zjcxjc.cn"):
                logger.info(f"{field_name}已迁移，无需重复备份")
                new_attachments.append(attachment)
                continue
            else:
                full_download_url = yida_client.get_full_download_url(admin_user_id,download_url,True)
                download_url = full_download_url.body.result
            response = requests.get(download_url)
            if response.status_code == 200:
                file_content = response.content
                oss_path = f"{report_path}/{field_name}/{index}-{attachment.get('name')}"
                bucket.put_object(oss_path, file_content)
                xm_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_path}"
                new_attachment = {
                        "downloadUrl": xm_url,
                        "name": attachment.get('name'),
                        "previewUrl": xm_url,
                        "url": xm_url,
                        "ext": attachment.get('name').split('.')[-1]
                    }
                new_attachments.append(new_attachment)
        yida_client.update_form_data_by_id(form_uuid, admin_user_id, form_inst_data.form_instance_id, {
                    field_name: new_attachments
                })
        logger.info(f"{field_name}备份迁移成功")
    except Exception as e:
        print(f"宜搭接口调用错误：{e}")
        retry -= 1
        if retry > 0:
            bak_attachment(form_inst_data,field_name,report_path,form_uuid,retry)
        else:
            logger.info(f"{field_name}备份迁移失败")
            raise e


def record_log(form_inst_id):
    with open("yida_app_service/chengxiang/resorce/bak_lists/trans_err.txt", "a", encoding="utf-8") as file:
        file.write(f"{form_inst_id}\n")